#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

#include "help/query.h"
#include "help/util.h"

int main(int argc, char* argv[]) {
    if (argc < 5) {
        return 1;
    }

    char* user = argv[1];
    char* unit = argv[2];
    float dest_x = atol(argv[3]);
    float dest_y = atol(argv[4]);
    char* root = getenv("RELAT_ROOT");

    float x, y, z;
    query_unit_position(user, unit, &x, &y, &z);

    char unit_pos_file_name[256];
    sprintf(unit_pos_file_name, "%s/%s/%s/position", root, user, unit);

    FILE* unit_pos_file;
    if ((unit_pos_file = fopen(unit_pos_file_name, "w+")) == NULL) {
        perror("could not open position file for unit");
        exit(-1);
    }

    fprintf(unit_pos_file, "%.3f %.3f %.3f", x, y, z);

    char unit_move_file_name[256];
    sprintf(unit_move_file_name, "%s/%s/%s/move", root, user, unit);

    FILE* unit_move_file;
    if ((unit_move_file = fopen(unit_move_file_name, "w+")) == NULL) {
        perror("could not open move file for unit");
        exit(-1);
    }

    float dx = dest_x - x;
    float dy = dest_y - y;

    float length = sqrt(dx * dx + dy * dy);
    if (length != 0) {
        dx /= length;
        dy /= length;
    }

    unsigned long current_time = get_unix_timestamp();
    unsigned long to = current_time + (unsigned long)(length * 1000);

    fprintf(unit_move_file, "%ul %ul %.3f %.3f %.3f", current_time, to, dx, dy, 0.0f);

    return 0;
}